package com.monkeygroup.mygoplus.ecchat.ui.chatting;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.base.BaseActivity;
import com.monkeygroup.mygoplus.ecchat.common.utils.PermissionUtils;
import com.monkeygroup.mygoplus.ecchat.ui.LocationInfo;
import com.monkeygroup.mygoplus.http.HttpModel;

import org.json.JSONArray;
import org.json.JSONObject;

public class MapsLocationActivity extends BaseActivity
        implements OnMapReadyCallback, View.OnClickListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        ActivityCompat.OnRequestPermissionsResultCallback {

    private LocationManager locationManager;
    private GoogleApiClient mGoogleApiClient;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    private static final int DEFAULT_ZOOM = 15;
    private final LatLng mDefaultLocation = new LatLng(25.021, 121.551);
    private final String lprovider = LocationManager.NETWORK_PROVIDER;
    private final String queryUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s&language=zh_cn&sensor=false";

    /**设置初始值，如果定位失败，用来测试**/
    private double lat = 25.021;
    private double lng = 121.551;
    private String address = "台灣原住民族圖書資訊中心(TIPRC)";
    private GoogleMap mMap;
    private final String TAG = "MapsLocation";

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_maps_location);
    }

    @Override
    public void initView() {

    }

    @Override
    public void setListener() {
        findViewById(R.id.layout_back).setOnClickListener(this);
        findViewById(R.id.layout_shortcut).setOnClickListener(this);
    }

    @Override
    public void doEvent() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */,
                        this /* OnConnectionFailedListener */)
                .addConnectionCallbacks(this)
                .addApi(LocationServices.API)
                .addApi(Places.GEO_DATA_API)
                .addApi(Places.PLACE_DETECTION_API)
                .build();
        mGoogleApiClient.connect();
    }

    private void getNetworkLocation() throws SecurityException {
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            Toast.makeText(this, "定位失敗，沒有運營商網絡！", Toast.LENGTH_SHORT).show();
            return;
        }

        Location location = locationManager.getLastKnownLocation(lprovider);
        refreshMap(location);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
        mMap.setTrafficEnabled(true);

//        // Add a marker in Sydney and move the camera
        mMap.addMarker(new MarkerOptions().position(mDefaultLocation).title("台灣原住民族圖書資訊中心(TIPRC)"));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));

        enableMyLocation();
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.d(TAG, "onConnected");
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.d(TAG, "onConnectionSuspended");
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(TAG, "onConnectionFailed");
    }

    /**
     * Enables the My Location layer if the fine location permission has been granted.
     */
    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            // Permission to access the location is missing.
            PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
                    Manifest.permission.ACCESS_FINE_LOCATION, true);
        } else {
            // Access to the location has been granted to the app.
            if (mMap != null) {
                getNetworkLocation();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
            return;
        }

        if (PermissionUtils.isPermissionGranted(permissions, grantResults,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Enable the my location layer if the permission has been granted.
            enableMyLocation();
        } else {
            Toast.makeText(this, "沒有授予權限，定位失敗", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onStop() {
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
        super.onStop();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_back:
                finish();
                break;
            case R.id.layout_shortcut:
                Intent intent = new Intent();
                LocationInfo locationInfo = new LocationInfo();
                locationInfo.setLat(lat);
                locationInfo.setLon(lng);
                locationInfo.setAddress(address);
                intent.putExtra("location", locationInfo);
                setResult(ChattingActivity.RESULT_OK, intent);
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 利用網絡獲取具體地址
     **/
    private void queryLocation() {
        String url = String.format(queryUrl, lat, lng);

        HttpModel httpModel = new HttpModel(url, new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {
                if (data == null)
                    return;

                String result = (String) data;
                try {
                    JSONArray jsonArray = new JSONObject(result)
                            .getJSONArray("results");

                    if (jsonArray.length() > 1) {
                        JSONObject jsonObject = jsonArray.getJSONObject(0);
                        address = jsonObject.optString("formatted_address");
                        Log.e("Add", address);
                    }

                    LatLng currPosition = new LatLng(lat, lng);
                    mMap.addMarker(new MarkerOptions()
                            .title("當前位置")
                            .position(currPosition)
                            .snippet(address));

                    // Position the map's camera at the location of the marker.
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currPosition,
                            DEFAULT_ZOOM));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, true);

        httpModel.Request();
    }

    private void refreshMap(Location location) {
//        List<Address> addList = null;

//        Geocoder ge = new Geocoder(this);
        if (location != null) {
            lat = location.getLatitude();
            lng = location.getLongitude();
            queryLocation();

//            try {
//                addList = ge.getFromLocation(lat, lng, 1);
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//            if (addList != null && addList.size() > 0) {
//                Address ad = addList.get(0);
//                address = ad.getLocality() + " " + ad.getSubLocality();
//            }
//
//            LatLng currPosition = new LatLng(lat, lng);
//            mMap.addMarker(new MarkerOptions()
//                    .title("當前位置")
//                    .position(currPosition)
//                    .snippet(address));
//
//            // Position the map's camera at the location of the marker.
//            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currPosition,
//                    DEFAULT_ZOOM));

        } else {
            Toast.makeText(this, "定位失敗", Toast.LENGTH_SHORT).show();
        }

    }

}
